package com.guli.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.guli.common.result.Result;
import com.guli.vod.service.VodService;
import com.guli.vod.util.AliyunVODSDKUtils;
import com.guli.vod.util.ConstantPropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("vod")
@CrossOrigin
public class UploadVodController {

    @Autowired
    private VodService vodService;


    /**
     * 根据视频id获取视频播放凭证
     *
     * @param
     * @return id
     */
    @GetMapping("getPlayAuthFront/{vid}")
    public Result getPlayAuthFront(@PathVariable String vid) {
        // 1 初始化对象
        try {
            DefaultAcsClient client = AliyunVODSDKUtils.initVodClient(ConstantPropertiesUtil.ACCESS_KEY_ID, ConstantPropertiesUtil.ACCESS_KEY_SECRET);

            // 2 创建获取播放凭证的request对象

            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.setVideoId(vid);

            // 3 调用方法返回response对象
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            System.out.println("视频播放凭证："+ playAuth);

            return Result.ok().data("playAuth", playAuth);

        } catch (Exception e) {
            return null;
        }
    }

    @PostMapping("upload")
    public Result upload(MultipartFile file){
        String videoSourceId = vodService.upload(file);
        return Result.ok().data("videoSourceId", videoSourceId);
    }

    /**
     * 根据视频ID获取播放凭证
     * @return
     */
    @DeleteMapping("{videoSourceId}")
    public Result getVideoPlayAuth(@PathVariable String videoSourceId){
        Boolean flag = vodService.deleteVodById(videoSourceId);
        if(flag){
            return Result.ok();
        }
        return Result.error();
    }

    /**
     * 根据多个视频ID删除视频
     * @param videoIdList
     * @return
     */
    @DeleteMapping("removeList")
    public Result getRemoveList(@RequestParam("videoIdList") List videoIdList){

        Boolean flag = vodService.getRemoveListByIds(videoIdList);
        if(flag){
            return Result.ok();
        }
        return Result.error();
    }


}
